import { ref, computed, Ref } from 'vue';
import { useRouter } from 'vue-router';

// 表格列配置接口
export interface TableColumn {
  prop?: string;
  label: string;
  width?: string | number;
  fixed?: boolean | 'left' | 'right';
  type?: 'selection' | 'index' | 'expand';
  slot?: string | ((row?: any) => string); // 自定义插槽名称
  formatter?: (row: any, column: any, cellValue: any, index: number) => string;
  sortable?: boolean;
  align?: 'left' | 'center' | 'right';
  onClick?: (row: any) => void;
  buttonText?: string; // 按钮文本
  buttonType?: 'primary' | 'success' | 'warning' | 'danger' | 'info'; // 按钮类型
  link?: boolean; // 是否为链接样式
  buttonSize?: 'small' | 'default' | 'large'; // 按钮大小
  hasPermi?: string[]; // 按钮权限控制
  show?: (row?: any) => boolean; // 控制是否显示,
  checkSelectable?: (row: any) => boolean; // 选择项是否可选

  // input 相关
  disabled?: boolean;
  readonly?: boolean;
  clearable?: boolean;
  columnType?: (row: any) => string; // 控制列的类型
  handler?: (row: any) => void;
  blur?: (row: any) => void;

  // select 相关
  placeholder?: string;
  multipleLimit?: number;
  multiple?: boolean;
  collapseTags?: boolean;
  maxCollapseTags?: number;
  showCheckbox?: boolean;

  change?: ($event?: any, row?: any) => void;
  options?:
    | Array<{ label: string; value: any; disabled?: boolean }>
    | (() => Array<{ label: string; value: any; disabled?: boolean }>)
    | { value: Array<{ label: string; value: any; disabled?: boolean }> };

  showColumn?: (row?: any) => boolean; // 控制是否显示单个,
}

// 操作按钮配置接口
export interface ActionButton {
  label: string;
  type?: 'primary' | 'success' | 'warning' | 'danger' | 'info';
  color?: string;
  show?: (row: any) => boolean; // 控制按钮显示条件
  handler: (row: any) => void;
  link?: boolean;
  hasPermi?: string[]; // 按钮权限控制
  disabled?: boolean | ((row: any) => boolean);
}

// Hook 参数接口
export interface UseElTableOptions {
  data: any[]; // 表格数据
  columns: TableColumn[]; // 列配置
  actions?: ActionButton[]; // 操作按钮配置
  selection?: boolean; // 是否显示选择列
  height?: string | number; // 表格高度
  infiniteScroll?: boolean | Ref<boolean>; // 是否启用无限滚动，支持响应式
  cellClickRoute?: string; // 单元格点击跳转路由前缀
  rowKey?: string; // 行数据的 Key，用于跳转路由
  maxActions?: number | string; // 最多显示的操作按钮数量 / 操作列的宽度
  showActions?: boolean;
  actionText?: string;
}

export function useElTable(options: UseElTableOptions) {
  const router = useRouter();

  // 响应式数据
  const selectedRows = ref<any[]>([]);
  const loading = ref(false);

  // 处理 infiniteScroll 参数，支持响应式和普通布尔值
  const infiniteScrollEnabled = computed(() => {
    if (typeof options.infiniteScroll === 'boolean') {
      return options.infiniteScroll;
    }
    // 如果是 Ref，则返回其值
    return options.infiniteScroll?.value || false;
  });

  const showActions = computed(() => {
    // 设置默认值为true
    if (options.showActions === undefined) {
      return true;
    }
    return options.showActions;
  });

  // 计算属性 - 完整的列配置（包含选择列和操作列）
  const tableColumns = computed(() => {
    const cols: TableColumn[] = [];

    // 添加选择列
    if (options.selection) {
      cols.push({
        type: 'selection',
        width: 55,
        fixed: true,
        label: ''
      });
    }

    // 添加配置的列
    options.columns.forEach((item) => {
      if (item.show === undefined || item.show()) {
        cols.push(item);
      }
    });
    // cols.push(...options.columns);

    // 添加操作列
    if (options.actions && options.actions.length > 0 && !showActions.value) {
      // 过滤出options.actions中label长度最大的数量
      const maxLabelLength = Math.max(...options.actions.map((action) => action.label.length));
      cols.push({
        label: options.actionText || '操作',
        fixed: 'right',
        width:
          typeof options.maxActions == 'number'
            ? options.maxActions * (maxLabelLength * 18 + 20) + 5
            : options.maxActions, // 根据按钮数量动态计算宽度
        slot: 'actions'
      });
    }
    return cols;
  });

  // 处理选择变化
  const handleSelectionChange = (selection: any[]) => {
    selectedRows.value = selection;
    return selection;
  };

  // 处理单元格点击
  const handleCellClick = (row: any, column: any, cell: any, event: Event) => {
    if (options.cellClickRoute && options.rowKey && row[options.rowKey]) {
      router.push({
        path: `${options.cellClickRoute}/${row[options.rowKey]}`
      });
    }
    return { row, column, cell, event };
  };

  // 处理无限滚动加载
  const handleInfiniteScroll = () => {
    if (loading.value) return Promise.resolve();

    // 设置加载状态
    loading.value = true;

    // 返回一个简单的Promise，让调用者控制加载完成时机
    return Promise.resolve();
  };

  // 获取可见的操作按钮
  const getVisibleActions = (row: any): ActionButton[] => {
    if (!options.actions) return [];
    return options.actions.filter((action) => {
      return action.show ? action.show(row) : true;
    });
  };

  // 执行操作按钮点击
  const handleActionClick = (action: ActionButton, row: any, event: Event) => {
    event.preventDefault();
    event.stopPropagation();
    action.handler(row);
  };

  // 清空选择
  const clearSelection = () => {
    selectedRows.value = [];
  };

  // 设置加载状态
  const setLoading = (state: boolean) => {
    loading.value = state;
  };

  // 动态设置无限滚动状态（如果传入的是响应式引用）
  const setInfiniteScroll = (enabled: boolean) => {
    if (typeof options.infiniteScroll !== 'boolean' && options.infiniteScroll) {
      options.infiniteScroll.value = enabled;
    }
  };
  // 获取操作按钮的禁用状态
  const getActionDisabled = (action: ActionButton, row: any): boolean => {
    if (typeof action.disabled === 'function') {
      return action.disabled(row);
    }
    return action.disabled || false;
  };

  return {
    // 响应式数据
    selectedRows,
    loading,
    tableColumns,
    showActions,

    // 方法
    handleSelectionChange,
    handleCellClick,
    handleInfiniteScroll,
    getVisibleActions,
    handleActionClick,
    clearSelection,
    setLoading,
    setInfiniteScroll,
    getActionDisabled,

    // 配置
    tableHeight: options.height || '100%',
    infiniteScrollEnabled // 是否启用无限滚动
  };
}
